import { Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { ProjectMemberEntity } from '../entity/member';

/**
 * 项目成员
 */
@Provide()
export class ProjectMemberService extends BaseService {
    @InjectEntityModel(ProjectMemberEntity)
    projectMemberEntity: Repository<ProjectMemberEntity>;

    /**
     * 新增成员前检查
     */
    async modifyBefore(param: any) {
        // 检查是否已经是成员
        const exists = await this.projectMemberEntity.findOne({
            where: {
                projectId: param.projectId,
                userId: param.userId
            }
        });
        if (exists) {
            throw new Error('该用户已经是项目成员');
        }
    }

    /**
     * 修改成员角色前检查
     */
    async update(param: any) {
        const { id, roleType } = param;
        // 获取成员信息
        const member = await this.projectMemberEntity.findOne({
            where: { id }
        });
        if (!member) {
            throw new Error('成员不存在');
        }

        // 检查是否为项目的最后一个管理员
        if (member.roleType === 1 && roleType === 0) {
            const adminCount = await this.projectMemberEntity.count({
                where: {
                    projectId: member.projectId,
                    roleType: 1
                }
            });
            if (adminCount <= 1) {
                throw new Error('项目至少需要一名管理员');
            }
        }

        return super.update(param);
    }
} 